//
//  editMyResumeHightLight.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/5/3.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit 

enum editMyResumeHightLightLimitTags:Int{
    /**工作重点 */
    case Mystrength = 3
    /**我的亮点 */
    case Myheightlight = 5 //
}

class editMyResumeHightLight: UIViewController {

    var sendParamsClosure:((Dictionary<String,AnyObject>)->Void)?
    var topTitle:UILabel?
    var tagsView:LDBaseManySelTagsView?
    var lightTitle:String?
    //选择的数组
    var myLightTagsArr = [String]()
    var myLightTags_IDArr = [String]()
    //确认后dict
    var mySelHightIDParams = [String]()//NSMutableArray()
    //leve2Tags
    var leve2id = ""
    //
    var contentScrollView:UIScrollView?
    
    //网络保存的值
    var preSelHightIDParams = [String]()
    var limitTags:editMyResumeHightLightLimitTags = .Myheightlight
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setDefaultContent()
        requestNetwork()
    }
    
    override func viewDidAppear(animated: Bool) {
        let maxY = tagsView!.totalLabHeight + 80 + LDFrame.NavH
        contentScrollView?.contentSize = CGSizeMake(LDFrame.ScreenWidth, maxY)
        view.layoutIfNeeded()
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        setNav()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func requestNetwork() {
       
        if limitTags == .Myheightlight {
            
            tagsView?.limitTags = limitTags.rawValue
            LDCheckPublicInfo.shareInstance.checkoutMyHeightLight { [weak self] (data) in
                self?.setupTagsView(data)
            }
            
        } else if limitTags == .Mystrength {
            
            tagsView?.limitTags = limitTags.rawValue
            LDCheckPublicInfo.shareInstance.checkoutAllMainJobFocus(leve2id, closure: { [weak self] (data) in
                self?.setupTagsView(data)
            })
        }
        
    }
    
    
    func setupTagsView(arrData:Array<NSDictionary>) {
        
        for item in arrData {
            
            let params = item as! Dictionary<String,String>
            
            myLightTagsArr.append(params["tag_text"]!)
            myLightTags_IDArr.append(params["tag_id"]!)
            
        }

        tagsView?.titleParams = myLightTagsArr
        
        //网络保存的值 text －> id
        var arrID = Array<String>()
               
        if preSelHightIDParams.count > 0 {
            
            let count = myLightTags_IDArr.count
            for i in 0..<count {
                
                let item = myLightTags_IDArr[i]
                
                if preSelHightIDParams.contains(item) {
                    let idstr = String.init(format: "%d", i)
                    arrID.append(idstr)
                }
            }
            
            tagsView?.preSelLabID = arrID
        }
    }
    
    func setDefaultContent() {
        
        
        contentScrollView = UIScrollView.init(frame: LDFrame.ScreenBounds)
        contentScrollView!.backgroundColor = LDGolbalColor.BgGoundGray
//        view.backgroundColor = LDGolbalColor.BgGoundGray
        
        topTitle = UILabel.setDetailsLab("输入选择标签,最多\(limitTags.rawValue)个", fontSize: 15, titleColor: LDFontColor.DeepGray, Alignment: .Center)
//        topTitle?.backgroundColor = UIColor.redColor()
        
        tagsView = LDBaseManySelTagsView()//.init(frame: LDFrame.ScreenBounds)
        
        tagsView?.sendTapAddHightLightBtn({ [weak self] in
            self?.pushView()
            })
        
        tagsView?.sendManyLabsParams({ [weak self] (params) in
            
            guard self != nil else {
                return
            }
            
            for item in params {
                print(item as? String)
            }
            
            var selid = [String]()
            
            let IntParams = params.map({ (index) -> Int in
                let selid = index as! String
                return (Int(selid)!) ?? 0
            })
            
            for item in IntParams {
                
                selid.append(self!.myLightTags_IDArr[item])
            }
            
            self?.mySelHightIDParams = selid
            
            })
        
        contentScrollView?.addSubview(topTitle!)
        contentScrollView?.addSubview(tagsView!)
        view.addSubview(contentScrollView!)

        
        topTitle!.snp_makeConstraints { (make) in
            make.top.equalTo(LDMargin_V*4)
            make.width.equalTo(LDFrame.ScreenWidth)
            make.height.equalTo(30)
        }
        
        tagsView?.snp_makeConstraints (closure: { (make) in
            
            make.top.equalTo((topTitle?.snp_bottom)!)
            make.width.equalTo(LDFrame.ScreenWidth)
            make.height.equalTo(view.height - 100)
//            print(tagsView?.totalLabHeight,"tagsView?.totalLabHeight")
        })
    }
    
    //添加新标签按钮 暂时 hidden
    func pushView() {
        
        let alertController = UIAlertController(title: "添加新亮点", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        
        alertController.addTextFieldWithConfigurationHandler {
            (textField: UITextField!) -> Void in
            textField.placeholder = "输入亮点"
            textField.delegate = self
        }
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        
        let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default, handler:{
            [weak self](action) in
            self?.sendTags()
        })
        
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        
        navigationController?.presentViewController(alertController, animated: true, completion: nil)
    }
    
    func updateTagsView() {
    

    }
    
    func sendTags() {

        var params = [String:AnyObject]()
        params["tagsNum"] = mySelHightIDParams.count
        
        params["tagsIDs"] = mySelHightIDParams
        let dict = ["tags":params.jsonString()]
        print(params.jsonString())
        print(dict)
        if limitTags == .Mystrength {
            if sendParamsClosure != nil {
                sendParamsClosure!(params)
            }
            navigationController?.popViewControllerAnimated(true)
            return
        }
        
        LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.set.highlight, parameters: dict, success: { (value) in
            
            LDUserInfo.sharedInstance.updataJobFinderMyResume(nil, failure: nil)
            LDShowHUB.shareInstance.showSucc(value as! String)
            
        }) { (data, error) in
            
            LDShowHUB.shareInstance.showErr(data as! String)
        }
        navigationController?.popViewControllerAnimated(true)
    }
    
    //回调
    func getParmasFromSelTags(closure:(dict:Dictionary<String,AnyObject>)->Void) {
        sendParamsClosure = closure
    }
    
    func setNav() {
        let rightBar = UIBarButtonItem.init(image: UIImage.init(named: "common_nav_ok"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(sendTags))
        navigationItem.rightBarButtonItem = rightBar
    }
}
extension editMyResumeHightLight:UITextFieldDelegate {
    
    func textFieldDidEndEditing(textField: UITextField) {
        
    }
}
